package com.yourcompany.handle;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelHandler.Sharable;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;

/**
 * web管理对应的类
 * @author tzj
 *
 * 2016-11-24  下午5:00:45
 */
@Sharable
public class AdminHandle extends ChannelInboundHandlerAdapter{

	
	private  int  LOGIN=0x87654321;
	
	Channel channel;
	
	Logger logger = Logger.getLogger("server");
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		super.channelInactive(ctx);
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		ByteBuf buf = (ByteBuf) msg;
		buf.resetReaderIndex();
		
		int mask=buf.readInt();
		
		if(mask==LOGIN){
		
			
			ByteBuf byteBuf=ctx.alloc().buffer();
			byte[] bs=new byte[buf.readableBytes()];
			buf.readBytes(bs);
			JSONObject jsonObject=JSONObject.parseObject(new String(bs,"utf-8"));
			String username=jsonObject.getString("username");
			String password=jsonObject.getString("password");
			
			Map<String, Object> result=new HashMap<String, Object>();
			if("admin".equals(username)&&"admin".equals(password)){
				result.put("state", "ok");
				channel=ctx.channel();
				logger.debug("admin成功登录"+channel);
			}else{
				result.put("state", "fail");
			}
			byteBuf.writeInt(LOGIN);
			ctx.writeAndFlush(
					byteBuf.writeBytes(
							(new JSONObject(result).toJSONString().getBytes()))
					);
			
		}else{
			ctx.fireChannelRead(msg);
		}
		
		
	}
	
  
	/**
	 * 向管理端推送消息
	 * tzj 2016-11-24 下午5:26:16
	 */
	public void  pushMsg2AdminJson(ByteBufAllocator allocator,String json){
		
		if(channel!=null){
			channel.writeAndFlush(
					allocator.buffer().writeBytes(json.getBytes()));
		}
	}

	public void  pushMsg2AdminBuf(ByteBufAllocator allocator,ByteBuf buf){
		
		if(channel!=null){
			channel.writeAndFlush(
					buf
					);
		}
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		super.exceptionCaught(ctx, cause);
	}

	
}
